<!DOCTYPE html>
<html>

<head>
    <title>客服</title>
</head>

<body>
    <button onclick="setupWebSocket()">连接</button>
    <input type="text" id="messageInput" placeholder="Type a message...">
    <button onclick="sendMessage()">发送</button>
    <button onclick="closeWebSocket()">断开</button>
    <div id="chatArea" style="height: 300px; overflow-y: scroll;"></div>

    <script>
        const chatArea = document.getElementById('chatArea');
        const messageInput = document.getElementById('messageInput');
        let ws;

        function generateRandomString(length) {
            let result = '';
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

            for (let i = 0; i < length; i++) {
                const randomIndex = Math.floor(Math.random() * characters.length);
                result += characters.charAt(randomIndex);
            }

            return result;
        }

        function appendMessage(message) {
            const p = document.createElement('p');
            p.textContent = message;
            chatArea.appendChild(p);
        }

        function sendMessage() {
            const message = messageInput.value;
            if (message.trim() !== '') {

                const website_id = 5;
                const service_id = 3;
                const customer_id = 1;
                // 消息内容
                const msg = {
                    "content":message,
                    'round':'s2c',
                    'website_id':website_id,
                    'service_id':service_id,
                    'customer_id':customer_id
                }

                const str = JSON.stringify(msg);
                ws.send(str);
                messageInput.value = '';
            }
        }

        function setupWebSocket() {
            // let token = generateRandomString(10);
            let token = "2e574adeea5b847af6ea525a5fa5a636";
            // Replace with your WebSocket server URL
            // ws = new WebSocket('ws://127.0.0.1:7272?website_id=5&service_id=3'); 
            ws = new WebSocket('wss://www.aivodesk.com/ws?website_id=5&service_id=3'); 

            ws.onopen = () => {
                appendMessage('Connected to WebSocket server');
            };

            ws.onmessage = (event) => {
                appendMessage(`Received: ${event.data}`);
            };

            ws.onclose = () => {
                appendMessage('WebSocket connection closed');
            };

            ws.onerror = (error) => {
                appendMessage(`WebSocket error: ${error}`);
            };
        }
        function closeWebSocket(){
            ws.close();
        }

        // window.onload = setupWebSocket;
    </script>
</body>

</html>